<template>
    <div class="box">
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="username" name="username" label="用户名" placeholder="用户名"
                    :rules="[{  pattern, message: '请输入正确内容', required: true, message: '请填写用户名' }]" />
                <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
                <van-field v-model="sms" center clearable label="短信验证码" placeholder="请输入短信验证码">
                    <template #button>
                        <van-button size="small" type="primary" @click="getCode()" :disabled="time > 0 ? true : false">{{ time > 0 ? time+
                            "s后获取验证码" : "获取验证码" }}</van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    登录
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup>
import { ref } from 'vue';

import { loginApi } from '@/api/api';

import { showSuccessToast, showFailToast } from 'vant';

const username = ref('');
const password = ref('');
const sms = ref('')
const time = ref(0)
const onSubmit = (values) => {
    console.log('submit', values);
    loginApi(username.value, password.value).then((res) => {
        console.log(res)
        if (res.data.code == 0) {
            showSuccessToast(res.data.msg);
            localStorage.setItem("token",res.data.data.token)
            localStorage.setItem("username",res.data.data.username)
        } else {
            showFailToast(res.data.msg);
        }
    })
};

const pattern = /^1\d{10}$/.test(username) 

const getCode = () => {
    // console.log(Math.random().toString().slice(2, 8))
    sms.value = Math.random().toString().slice(2, 8)
    time.value = 10

    let timer = setInterval(() => {
        time.value--;
        if(time.value < 0){
            clearInterval(timer)
        }
        console.log(time.value)
    }, 1000);

}

</script>

<style lang="scss" scoped>
.box {
    width: 100%;
    height: 100%;
}
</style>